Repository navigation
feat(gemma4): lift specialised RMSNorm variants into MLXLMCommon (WS-C #7) - #179
Merged
Merged
Conversation
…#7) Conservative Gemma 4 consolidation: lift the two RMSNorm classes the VLM defines as `private final` (`Gemma4RMSNormNoScale`, `Gemma4RMSNormZeroShift`) into a new public `MLXLMCommon.Gemma4` namespace, mirroring the WS-C #5 (Qwen 3) and WS-C #6 (GLM 4) shape. Why only the norm classes - The LLM has substantial alpha-branch perf work that we explicitly preserve: compiled QKV projection, the `MLXFast.rmsNormRoPE` fused norm+rope kernel path (gated by `_fusedInvFreqs`), the conditional `Gemma4SharedMLP` gate+down compile (tuned ON for dense E2B/E4B/31B, OFF for MoE 26B-A4B per a measured ~10% regression), the fused logit softcap, and the fused gelu+mul PLE projection. Forcing a unified `Attention` / `MLP` / `DecoderLayer` would either silently regress these or impose an indirection on the LLM hot path. - The VLM's `Gemma4Text*` decoder is the upstream Python-port shape without the alpha-branch perf surgery; lifting only the bit-identical norm classes leaves the per-target instantiation pattern intact. - The LLM's existing `MLXNN.RMSNorm` uses are functionally equivalent to `MLXLMCommon.Gemma4.RMSNormZeroShift` (both init weight=ones and call `MLXFast.rmsNorm(x, weight, eps)`) and the inline `MLXFast.rmsNorm(weight: .mlxNone)` v_norm call is functionally equivalent to `MLXLMCommon.Gemma4.RMSNormNoScale`. Both equivalences are now annotated in the LLM file so the deliberate non-share is auditable rather than accidental. What's shared - `MLXLMCommon.Gemma4.RMSNormNoScale` — `MLXFast.rmsNorm(weight: .mlxNone)`. Used by VLM `Gemma4TextAttention.v_norm` and `Gemma4TextRouter.norm`. - `MLXLMCommon.Gemma4.RMSNormZeroShift` — `MLXFast.rmsNorm(weight: weight)` with `weight = ones` initialisation, no `(1 + weight)` shift (per the original Gemma 1/2 family). Used by every layer norm + q_norm + k_norm in the VLM text decoder. What's NOT shared (documented in the file-level note) - Attention / MLP / DecoderLayer / Backbone — see the "alpha-branch perf work" rationale above. - `ProportionalRoPE` — the LLM defines a Gemma 4-tuned variant (inf-padded freqs to pass-through unrotated dims) at `Libraries/MLXLLM/Models/Gemma4.swift:221`; the VLM dispatches via `initializeRope` to `MLXLMCommon.RoPEUtils.ProportionalRoPE` (general-purpose, split-pair algorithm). The two intentionally diverge to match the upstream Python ports of their respective reference implementations; unifying them is a correctness check out of scope for this sprint. KV-shared MLP gap (per WS-C plan) - Both LLM (`Gemma4SharedMLP` lines 538–592) and VLM (`Gemma4TextMLP` lines 478–498) implement the double-wide MLP path identically: `useDoubleWideMlp` is consulted but only activates when `numKvSharedLayers > 0`. Default config values diverge — LLM defaults to `false`, VLM defaults to `true` — but both are functionally equivalent for the current model set (no shipped Gemma 4 checkpoint sets `numKvSharedLayers > 0`). Documenting here rather than fixing — `useDoubleWideMlp` is genuinely unused without KV sharing and the field-decay isn't user-visible. Future-work alignment with `IMPLEMENTATION-PLAN.md` - **Spec 024 — KV cache write fusion** (Tier 4). Gemma 4 E2B was the trigger model for the 60-copy decode-path regression; the shared K/V update pattern that spec lifts is what would justify a consolidated `Gemma4DecoderLayer` here. - **Spec 029 — ANE LM head + Gemma 4 PLE projection**. PLE projection is the natural ANE-offload boundary; a consolidated `Gemma4Backbone` would expose it cleanly. - **Issue #115 — `MLXFast.batchedQKVQuantizedGEMV`** + **issue #117 — RMSNorm + GEMV fusion**. Today the LLM uses `MLXFast.rmsNormRoPE` (a similar fused kernel) only for Gemma 4; when those issues land, both attention paths converge on the same primitive and an `Attention` consolidation becomes safe. - **Cross-family M-RoPE helper** (deferred from PR #177 / #178). Gemma 4 doesn't need it (no multimodal positionIds stack), but unblocks the same kind of second-pass consolidation here. Verification (M1 Max 64GB) - `swift build` clean across LLM + VLM + Common targets. - `swift test --filter Gemma4` — 7/7 tests pass (configuration dual decoding + UserInput modality ordering + nested rope params). - LLM smoke (`mlx-community/gemma-4-e2b-it-4bit`, kv=none, simple): 307.3 tok/s prefill, 92.0 tok/s decode, 126ms TTFT, 2.60GB peak. Coherent output: "Hello! I am a helpful assistant. I can help you with various tasks like answering questions, generating text, summarizing information, and more. How c…" - VLM smoke (`mlx-community/gemma-4-e2b-it-4bit`, kv=none, vision): 449.2 tok/s prefill, 103.1 tok/s decode, 666ms TTFT, 4.65GB peak. Coherent output: "This is a photograph of a dog, likely a Golden Retriever, standing outdoors in front of a house." — issue #169 prefill-sync barrier still working (no `<pad>` flood). Closes one of the 8 WS-C consolidation entries listed under issue #168. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closed
3 of 4 tasks
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…kryski#179) * style: format DiffusionGemmaVisionOracleTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: format DiffusionGemmaFactoryTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: run bit-exact reference tests only on reference hardware Nine DiffusionGemma tests compare float bits with frozen references. On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits, with no change in shape, dtype or sign. Add a `.referenceHardware` Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1, and mark the nine tests with it. Elsewhere they report as skipped with the reason. No assertion, tolerance or reference changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the bit comparisons of mixed DiffusionGemma tests Three gated tests also held checks that pass on any hardware. Split them so only the bit-for-bit comparison is gated: - prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its fail-closed probes on all hardware. The donor-logits bit comparison moves to failClosedProbesLeaveDonorLogitsBitExact(). - nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and model-release checks on all hardware. The logits bit comparison moves to nativeFactoryDenoiseMatchesReferenceBits(). - The two parameterized vision tests run their bf16 case on all hardware. The fp32 case moves to a separate gated test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the reference comparisons of three more DiffusionGemma tests Split the three tests that were still gated whole, so their checks that pass on any hardware run everywhere: - chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the prefill bounds, the complete flag, the counters, cancel, the emitted checkpoint and the released cache for widths 1, 3 and 7. The KV and logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference(). - sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture checks, both cache positions and the unchanged encoder KV after the provisional canvas. The reference comparisons stay in sharedWeightsConditioningAndCommittedCacheMatchReference(). - committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the token count, retained bytes, donor release and both positions. The reference comparisons stay in committedPrefixRestoreIsExactAfterDonorAppendAndRetirement(). Each pair shares one helper. The fixture reference, case-count and parameter-count checks of the block and fp32 vision fixtures also run everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned(). CONTRIBUTING.md says which comparisons the gate covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: format HistoricalWindowCheckpointTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: size the slot-cap request from what the ledger accepts slotCapLeavesRoomForServing() sized its request from bytesReserved. bytesReserved includes the paged pool's physical-floor overhead, which a request's target KV replaces when it reserves. The overhead depends on the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a 49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide cache. When earlier work left 64 KiB buffers in the cache, the capped arm left more than 5.5 windows of real slack instead of half a window, and the uncapped arm's reservation fit. Find the largest request the ledger accepts beside the capped set with trial reservations, then take half a window off it. The assertions do not change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: add test types and a unit test step without the Metal library Add the Swift Testing tags unit, kernel, integration and reference in Tests/MLXLMTests/TestTypeTags.swift, and the UnitTests parent suite that gives the unit tag to the suites under Tests/MLXLMTests/Unit. Fork Tests runs the unit tests before it builds the Metal library. swift test cannot select tests by tag, so the step selects the UnitTests suite by name. CONTRIBUTING.md describes the four types. Add two example unit suites for JSONValue and ToolCall.execute. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: select the UnitTests suite of every test target Other test targets, such as MLXLMServerTests, can then add unit tests with their own TestTypeTags.swift and no change to the workflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: apply review fixes to the test type convention - Delete every cached *.metallib, not only mlx.metallib, before the build and before the cache is saved, so the unit step guard sees the same set of files. - The guard prints the found libraries, then one ::error:: line. - Add scripts/check-unit-test-files.sh: it fails when a Swift file under Tests/<Target>/Unit/ has no extension UnitTests. The unit step runs it, and scripts/test-run-nested-suite.sh proves it red on a bad file. - CONTRIBUTING.md: folders for each test target, the sentence on files without a type tag, and the section Xcode integration tests. - fork.yaml: unit tests are under Tests/<Target>/Unit/ for each test target; describe the new script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
WS-C #7: lift the two specialised RMSNorm variants the VLM defines as
private final(Gemma4RMSNormNoScale,Gemma4RMSNormZeroShift) into a new publicMLXLMCommon.Gemma4namespace. Conservative scope on purpose — see the why only the norm classes section.Why only the norm classes
The LLM has substantial alpha-branch perf work that we explicitly preserve rather than consolidate away:
MLXFast.rmsNormRoPEfused norm+rope kernel path (gated by_fusedInvFreqs)Gemma4SharedMLPgate+down compile (tuned ON for dense E2B/E4B/31B, OFF for MoE 26B-A4B per a measured ~10% regression)Forcing a unified
Attention/MLP/DecoderLayerwould either silently regress these or impose an indirection on the LLM hot path. The VLM'sGemma4Text*decoder is the upstream Python-port shape without the alpha surgery; lifting only the bit-identical norm classes leaves the per-target instantiation pattern intact.Functional equivalences are now annotated in Libraries/MLXLLM/Models/Gemma4.swift so the deliberate non-share is auditable rather than accidental:
MLXNN.RMSNorm(LLM, used everywhere) ≡MLXLMCommon.Gemma4.RMSNormZeroShift— both initweight = onesand callMLXFast.rmsNorm(x, weight, eps).MLXFast.rmsNorm(weight: .mlxNone)(LLM, used for v_norm) ≡MLXLMCommon.Gemma4.RMSNormNoScale.What's shared
MLXLMCommon.Gemma4.RMSNormNoScale—MLXFast.rmsNorm(weight: .mlxNone). Used by VLMGemma4TextAttention.v_normandGemma4TextRouter.norm.MLXLMCommon.Gemma4.RMSNormZeroShift—MLXFast.rmsNorm(weight: weight)withweight = onesinitialisation, no(1 + weight)shift (per the original Gemma 1/2 family). Used by every layer norm + q_norm + k_norm in the VLM text decoder.What's NOT shared (documented in the file-level note)
ProportionalRoPE— the LLM defines a Gemma 4-tuned variant (inf-padded freqs to pass-through unrotated dims) at Libraries/MLXLLM/Models/Gemma4.swift:221; the VLM dispatches viainitializeRopetoMLXLMCommon.RoPEUtils.ProportionalRoPE(general-purpose, split-pair algorithm). The two intentionally diverge to match the upstream Python ports; unifying them is a correctness check out of scope for this sprint.KV-shared MLP gap (per WS-C plan)
Both LLM (
Gemma4SharedMLP) and VLM (Gemma4TextMLP) implement the double-wide MLP path identically:useDoubleWideMlpis consulted but only activates whennumKvSharedLayers > 0. Default config values diverge — LLM defaults tofalse, VLM totrue— but both are functionally equivalent for the current model set (no shipped Gemma 4 checkpoint setsnumKvSharedLayers > 0). Documenting here rather than fixing —useDoubleWideMlpis genuinely unused without KV sharing and the field-decay isn't user-visible.Future-work alignment with
IMPLEMENTATION-PLAN.mdGemma4DecoderLayerhere.Gemma4Backbonewould expose it cleanly.MLXFast.batchedQKVQuantizedGEMV+ issue perf(decode): RMSNorm + GEMV fusion for MLP and attention #117 — RMSNorm + GEMV fusion. Today the LLM usesMLXFast.rmsNormRoPE(a similar fused kernel) only for Gemma 4; when those issues land, both attention paths converge on the same primitive and anAttentionconsolidation becomes safe.Verification (M1 Max 64GB)
swift buildclean across LLM + VLM + Common targets.swift test --filter Gemma4— 7/7 tests pass (configuration dual decoding + UserInput modality ordering + nested rope params).<pad>flood).Test plan
Closes one of the 8 WS-C consolidation entries listed under issue #168.